import * as THREE from 'https://unpkg.com/three@0.132.2/build/three.module.js';
import { OrbitControls } from './js/o.js';
import Stats from './js/stats.module.js';

//创建场景
const scene = new THREE.Scene();

let stats

//创建相机 (角度，比例，近截面，远截面)
const camera = new THREE.PerspectiveCamera(80,window.innerWidth/window.innerHeight,
    0.1,1000);

//创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth,window.innerHeight);
document.body.appendChild(renderer.domElement);

//创建多彩材质
// const colorArr = ['red','green','blue','pink','orange','white']
// const materialArr = colorArr.map(colorStr=>{
//     return new THREE.MeshBasicMaterial({
//         color:colorStr
//     })
// })

let objArr = []

// 创建多个随机立方体
function createMore(){
    for (let i = 0; i < 5; i++) {
        const geometry = new THREE.BoxGeometry(getRandomSize(), getRandomSize(), getRandomSize())

        // const material = new THREE.MeshBasicMaterial({ color: `rgb(${getRandomColor()},${getRandomColor()},${getRandomColor()})` })
        // const cube = new THREE.Mesh(geometry, material)

        const colorArr = [getRandomColorStr(),getRandomColorStr(),getRandomColorStr(),getRandomColorStr(),getRandomColorStr(),getRandomColorStr()]
        const materialArr = colorArr.map(colorStr=>{
            return new THREE.MeshBasicMaterial({
                color:colorStr
            })
        })
        const cube = new THREE.Mesh(geometry, materialArr)

        cube.userData.index = i

        cube.position.x = getRandomPosition()
        cube.position.y = getRandomPosition()
        cube.position.z = getRandomPosition()
        objArr.push(cube)
        scene.add(cube)
    }
}

// 创建多个随机立方体
createMore()

// 创建单个立方体

// const geometry = new THREE.BoxGeometry(1,1,1);
// const material = new THREE.MeshBasicMaterial({color:0x00ff00});
// const cube = new THREE.Mesh(geometry,material);
// // const cube = new THREE.Mesh(geometry,materialArr);
// scene.add(cube);

camera.position.z = 25;
camera.position.x = 1;
camera.position.y = 1;

//创建标准材质球体
function createSphere(){
    const geometry = new THREE.SphereGeometry(1,32,32)
    const material = new THREE.MeshStandardMaterial({
        color:0xffff00
    })
    const mesh = new THREE.Mesh(geometry,material)
    scene.add(mesh)
}

//创建光源
function createLight(){
    //参数：颜色，亮度
    const directionalLight = new THREE.DirectionalLight(0xffffff,1)
    directionalLight.position.set(3,3,3)
    scene.add(directionalLight)

    //光源辅助对象 参数：光源对象，辅助线宽高
    const directionalLightHelper = new THREE.DirectionalLightHelper(directionalLight,2)
    scene.add(directionalLightHelper)
}

createSphere()
createLight()


//添加场景坐标系
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
renderer.render(scene,camera);

//添加轨道控制器
let controls;
function createOrbit(){
    controls = new OrbitControls(camera,renderer.domElement);
    controls.update();
}

//递归刷新帧
function animate(){
    requestAnimationFrame(animate);
    controls.update();
    stats.update()
    renderer.render(scene,camera);
}
//创建性能监视器
function createStats(){
    stats = new Stats()
    stats.setMode(0)
    stats.domElement.style.position = 'fixed'
    stats.domElement.style.top = 0
    stats.domElement.style.left = 0
    document.body.appendChild(stats.domElement)
}

//监听窗口尺寸改变
function resize(){
    window.addEventListener('resize',()=>{
        //设置画布尺寸
        renderer.setSize(window.innerWidth,window.innerHeight);
        camera.aspect = window.innerWidth/window.innerHeight;
        //更新摄像机矩阵空间
        camera.updateProjectionMatrix();
    })
}

const raycaster = new THREE.Raycaster()
const pointer = new THREE.Vector2()

function bindDBClick(){
    window.addEventListener('dblclick',(event)=>{
        pointer.x = (event.clientX/window.innerWidth) * 2 - 1
        pointer.y = -(event.clientY/window.innerHeight) * 2 + 1
        
        raycaster.setFromCamera(pointer,camera)
        
        objArr.forEach(o=>{
            console.log('ARR '+o.userData.index)
        })
        const list = raycaster.intersectObjects(objArr)
        list.forEach(o=>{            
            console.log('list '+o.object.userData.index)
        })
        if(list.length==0) return
        const cube = list[0].object
        
        cube.geometry.dispose()
        cube.material.forEach(material => material.dispose())
        scene.remove(cube)

        // objArr.splice(cube.userData.index,1)
        objArr = objArr.filter(o =>
            o != cube
        )
        objArr.forEach(o=>{
            console.log('arr '+o.userData.index)
        })        
        console.log('--------------')
    })

}

resize()
bindDBClick()
createStats();
createOrbit();
animate();


/************************************************ */
function getRandomSize(){
    return getRandomInt(1,5)
}

function getRandomPosition(){
    return getRandomInt(-8,8)
}

function getRandomColor(){
    return Math.floor(Math.random()*256)
}

function getRandomColorStr(){
    return `rgb(${getRandomColor()},${getRandomColor()},${getRandomColor()})`
}

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

